<?php

namespace App\Models\Arts;

use App\Models\BaseModel;
use App\Utils\Common;
use Fukuball\Jieba\Finalseg;
use Fukuball\Jieba\Jieba;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

class ArticleModel extends BaseModel
{
    use HasFactory;

    protected $table = 'article';
    public $timestamps = false;

    /**
     * 默认查询字段
     *
     * @var array|string[]
     */
    public array $select = [
        '*'
    ];

    /**
     * 筛选条件
     *
     * @param $query
     * @param $value
     * @param array $params
     * @return mixed
     */
    public function searchTypeIdAttribute($query, $value, array $params): mixed
    {
        if (empty($value)) {
            return $query;
        }
        return $query->where('type_id', $value);
    }

    public function searchKeywordAttribute($query, $value, array $params): mixed
    {
        if (empty($value)) {
            return $query;
        }

        // 分词搜索
        Jieba::init();
        Finalseg::init();
        $values = Jieba::cut($value);
        $query->where(function ($query) use ($values) {
            foreach ($values as $k=>$v){
                $query->orWhere('title','like', "%{$v}%");
            }
        });
        $query->orderBy(DB::raw('`title` LIKE "%'.$value.'%" DESC'));
        foreach ($values as $k=>$v){
            $query->orderBy(DB::raw('`title` LIKE "%'.$v.'%" DESC'));
        }

        return $query;
    }

    /**
     * 数据处理器
     * @param $value
     * @param $params
     * @return string
     */
    public function dataCreatedAtAttribute($value,$params)
    {
        if (empty($value)){
            return '---';
        }
        return date('Y-m-d H:i:s',$value);
    }

    public function dataImageAttribute($value,$params)
    {
        if (empty($value)){
            return '';
        }
        return Common::getHttp($value);
    }
}
